﻿using Furion;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using TouchSocket.Core;
using TouchSocket.Sockets;

namespace TcpClient.Web.Core
{
    // 后台服务类
    public class TcpClientBackgroundService : BackgroundService
    {
        private readonly ILogger<TcpClientBackgroundService> _logger;

        public TcpClientBackgroundService(ILogger<TcpClientBackgroundService> logger)
        {
            _logger = logger;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            var tcpClient = new TouchSocket.Sockets.TcpClient();
            tcpClient.Connecting = (client, e) => EasyTask.CompletedTask;
            tcpClient.Connected = (client, e) => EasyTask.CompletedTask;
            tcpClient.Closing = (client, e) => EasyTask.CompletedTask;
            tcpClient.Closed = (client, e) => EasyTask.CompletedTask;

            await tcpClient.SetupAsync(new TouchSocketConfig()
                .SetRemoteIPHost("127.0.0.1:1024")
                .ConfigureContainer(a => a.AddConsoleLogger()));

            await tcpClient.ConnectAsync();
            _logger.LogInformation("TCP 客户端成功连接");

            using (var receiver = tcpClient.CreateReceiver())
            {
                while (!stoppingToken.IsCancellationRequested) // 使用 stoppingToken 安全退出
                {
                    try
                    {
                        using (var receiverResult = await receiver.ReadAsync(stoppingToken))
                        {
                            if (receiverResult.IsCompleted)
                            {
                                _logger.LogInformation($"客户端已断开，信息：{receiverResult.Message}");
                                break;
                            } 

                            var mes = receiverResult.ByteBlock.ToString();
                            // 获取当前日期
                            var now = DateTime.Now;
                            string basePath = AppDomain.CurrentDomain.BaseDirectory;
                            // 创建年/月/日目录结构
                            string dayDir = Path.Combine(basePath, now.Year.ToString()+ now.Month.ToString("D2")+ now.Day.ToString("D2"));
                         
                            // 确保所有目录都存在
                             var ispath= EnsureDirectoryExists(dayDir);
                            _logger.LogInformation($"客户端接收到信息：{mes}");
                        }
                    }
                    catch (OperationCanceledException)
                    {
                        // 正常退出
                        break;
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, "TCP 接收异常");
                        await Task.Delay(1000, stoppingToken); // 防止频繁重试
                    }
                }
            }

            //await tcpClient.DisconnectAsync();
            _logger.LogInformation("TCP 客户端已关闭");
        }

        public static bool EnsureDirectoryExists(string path)
        {
            try
            {
             
                // 如果目录不存在则创建
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                    Console.WriteLine($"目录创建成功: {path}");
                    return true;
                }

                Console.WriteLine($"目录已存在: {path}");
                return false;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"创建目录失败: {ex.Message}");
                throw; // 或者返回false，取决于你的需求
            }
        }
    }
}
